<?php
/*
本系统由苏酷伊基于SiteHub项目二次开发
作者博客： https://www.sukuy.com/
后续更新地址： https://www.sukuy.com/navigation
作者QQ：3288637559
QQ交流群：884250547
任何第三方非官网在发布本系统时，不得删除该注释、版权信息、作者信息及官网等内容
*/
require('../includes/common.php');
require('../includes/lang.class.php');

if ($admin_islogin != 1) {
    exit("<script language='javascript'>window.location.href='./login.php';</script>");
}


if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        global $DB;
        
        
        $action = isset($_POST['action']) ? $_POST['action'] : '';
        
        
        if ($action == 'delete') {
            
            $days = isset($_POST['days']) ? intval($_POST['days']) : 0;
            
            
            if (!in_array($days, array(7, 30, 180, 365))) {
                echo json_encode(array('code' => 0, 'msg' => '无效的天数参数'));
                exit;
            }
            
            
            $delete_time = date('Y-m-d H:i:s', strtotime("-$days days"));
            
            
            $sql = "DELETE FROM pre_log WHERE create_time < '$delete_time'";
            $stmt = $DB->query($sql);
            $count = $stmt->rowCount();
            
            
            $count = is_numeric($count) ? $count : 0;
            
            
            $count = is_numeric($count) ? $count : 0;
            
            
            $day_text = '';
            switch($days) {
                case 7: $day_text = '一周'; break;
                case 30: $day_text = '一月'; break;
                case 180: $day_text = '半年'; break;
                case 365: $day_text = '一年'; break;
            }
            add_log('action', $conf['admin_user'], "删除{$day_text}之前的日志", 1);
            
            echo json_encode(array('code' => 1, 'msg' => '删除成功', 'count' => $count));
            exit;
        }
        
        
        if ($action == 'delete_all') {
            
            $count = $DB->delete('log', '1=1');
            
            $count = is_numeric($count) ? $count : 0;
            
            
            add_log('action', $conf['admin_user'], "清空所有日志", 1);
            
            echo json_encode(array('code' => 1, 'msg' => '清空成功', 'count' => $count));
            exit;
        }
        
        echo json_encode(array('code' => 0, 'msg' => '无效的操作'));
        exit;
    } catch (Exception $e) {
        echo json_encode(array('code' => 0, 'msg' => '操作失败: ' . $e->getMessage()));
        exit;
    }
}


$type = isset($_GET['type']) ? $_GET['type'] : '';


$title = $lang->admin->log;


$count = 0;


try {
    global $DB;
    $count = $DB->count('log');
} catch (Exception $e) {
    $count = 0;
}


$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$pagesize = 10;
$totalpage = ceil($count / $pagesize);
$page = min($totalpage, max(1, $page));
$offset = ($page - 1) * $pagesize;


if ($type) {
    $where = array('type' => $type);
    $title = $lang->admin->{'log_'.$type};
} else {
    $where = array();
}


$order = 'id DESC';


$logs = array();
try {
    global $DB;
    $logs = $DB->findAll('log', '*', $where, $order, $pagesize, $offset);
    if (empty($logs)) {
        $logs = array();
    }
} catch (Exception $e) {
    $logs = array();
}


$log_counts = array(
    'login' => 0,
    'email' => 0,
    'resetpwd' => 0,
    'verify' => 0,
    'action' => 0
);


$log_types = array('login', 'email', 'resetpwd', 'verify', 'action');


foreach ($log_types as $type) {
    try {
        global $DB;
        $log_counts[$type] = $DB->count('log', array('type' => $type));
    } catch (Exception $e) {
        $log_counts[$type] = 0;
    }
}


$title = $lang->admin->log;

require './header.php';
require './navbar.php';
require './sidebar.php';
?>

    <!-- 主内容区域 -->
    <div class="content-wrapper">
        <section class="content-header">
            <ol class="breadcrumb">
                <li><a href="index.php"><i class="fa fa-home"></i> <?php echo $lang->admin->index; ?></a></li>
                <li class="active"><?php echo $title; ?></li>
            </ol>
        </section>

        <section class="content">
            <div class="row">
                <div class="col-md-12">
                    <div class="box">
                        <div class="box-header with-border">
                            <h3 class="box-title"><?php echo $lang->admin->log_list; ?></h3>
                            <div class="box-tools pull-right">
                                <div class="btn-group" style="margin-right: 10px;">
                                    <button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                        <i class="fa fa-filter"></i> <?php echo $lang->admin->log_type; ?>
                                        <span class="caret"></span>
                                    </button>
                                    <ul class="dropdown-menu" role="menu">
                                        <li><a href="log.php"><i class="fa fa-list"></i> 全部日志 (<?php echo $count; ?>)</a></li>
                                        <li><a href="log.php?type=login"><i class="fa fa-sign-in"></i> <?php echo $lang->admin->log_login; ?> (<?php echo $log_counts['login']; ?>)</a></li>
                                        <li><a href="log.php?type=email"><i class="fa fa-envelope"></i> <?php echo $lang->admin->log_email; ?> (<?php echo $log_counts['email']; ?>)</a></li>
                                        <li><a href="log.php?type=resetpwd"><i class="fa fa-key"></i> <?php echo $lang->admin->log_resetpwd; ?> (<?php echo $log_counts['resetpwd']; ?>)</a></li>
                                        <li><a href="log.php?type=verify"><i class="fa fa-shield"></i> <?php echo $lang->admin->log_verify; ?> (<?php echo $log_counts['verify']; ?>)</a></li>
                                        <li><a href="log.php?type=action"><i class="fa fa-cog"></i> <?php echo $lang->admin->log_action; ?> (<?php echo $log_counts['action']; ?>)</a></li>
                                    </ul>
                                </div>
                                
                                <div class="btn-group" style="margin-right: 10px;">
                                    <button type="button" class="btn btn-warning btn-xs dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                                        <i class="fa fa-trash"></i> 日志清理
                                        <span class="caret"></span>
                                    </button>
                                    <ul class="dropdown-menu" role="menu">
                                        <li><a href="#" onclick="deleteLog(7)">删除一周之前的日志</a></li>
                                        <li><a href="#" onclick="deleteLog(30)">删除一月之前的日志</a></li>
                                        <li><a href="#" onclick="deleteLog(180)">删除半年之前的日志</a></li>
                                        <li><a href="#" onclick="deleteLog(365)">删除一年之前的日志</a></li>
                                        <li class="divider"></li>
                                        <li><a href="#" onclick="deleteAllLog()" style="color: #d9534f;">清空所有日志</a></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="box-body">

                            
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th><?php echo $lang->admin->log_type; ?></th>
                                            <th><?php echo $lang->admin->user; ?></th>
                                            <th><?php echo $lang->admin->log_action; ?></th>
                                            <th>IP地址</th>
                                            <th>操作结果</th>
                                            <th>操作时间</th>
                                            <th>详细信息</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if ($logs): ?>
                                            <?php foreach ($logs as $log): ?>
                                                <tr>
                                                    <td><?php echo $log['id']; ?></td>
                                                    <td>
                                                        <span class="label label-<?php 
                                                            switch($log['type']) {
                                                                case 'login': echo 'primary'; break;
                                                                case 'email': echo 'info'; break;
                                                                case 'resetpwd': echo 'warning'; break;
                                                                case 'verify': echo 'success'; break;
                                                                case 'action': echo 'default'; break;
                                                                default: echo 'danger';
                                                            }
                                                        ?>">
                                                            <?php echo $lang->admin->{'log_'.$log['type']}; ?>
                                                        </span>
                                                    </td>
                                                    <td><?php echo $log['username'] ? $log['username'] : '-'; ?></td>
                                                    <td><?php echo $log['action']; ?></td>
                                                    <td><?php echo $log['ip']; ?></td>
                                                    <td>
                                                        <span class="label label-<?php echo $log['result'] ? 'success' : 'danger'; ?>">
                                                            <?php echo $log['result'] ? '成功' : '失败'; ?>
                                                        </span>
                                                    </td>
                                                    <td><?php echo $log['create_time']; ?></td>
                                                    <td>
                                                        <button class="btn btn-xs btn-info" onclick="showDetail(<?php echo htmlspecialchars(json_encode($log), ENT_QUOTES, 'UTF-8'); ?>)">
                                                            <i class="fa fa-eye"></i> 查看
                                                        </button>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <tr>
                                                <td colspan="8" class="text-center text-muted">暂无日志记录</td>
                                            </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="box-footer clearfix">
                            <?php echo pagination("log.php?type=$type&page={page}", $page, $count, 10); ?>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>

    <!-- 页脚 -->
    <?php require './footer.php'; ?>
</div>

<!-- 详情模态框 -->
    <div class="modal fade" id="detailModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">日志详情</h4>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>日志ID：</label>
                                <span id="detail_id"></span>
                            </div>
                            <div class="form-group">
                                <label>日志类型：</label>
                                <span id="detail_type"></span>
                            </div>
                            <div class="form-group">
                                <label>操作用户：</label>
                                <span id="detail_username"></span>
                            </div>
                            <div class="form-group">
                                <label>操作内容：</label>
                                <span id="detail_action"></span>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>IP地址：</label>
                                <span id="detail_ip"></span>
                            </div>
                            <div class="form-group">
                                <label>操作结果：</label>
                                <span id="detail_result"></span>
                            </div>
                            <div class="form-group">
                                <label>操作时间：</label>
                                <span id="detail_time"></span>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>用户代理(User Agent)：</label>
                        <pre id="detail_useragent"></pre>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

<script>
// 解析User Agent信息
function parseUserAgent(userAgent) {
    if (!userAgent) return '-';
    
    let browser = '未知浏览器';
    let version = '未知版本';
    let os = '未知操作系统';
    
    // 检测浏览器
    if (userAgent.indexOf('Edg') > -1) {
        browser = 'Microsoft Edge';
        version = userAgent.match(/Edg\/(\d+\.\d+)/) ? userAgent.match(/Edg\/(\d+\.\d+)/)[1] : version;
    } else if (userAgent.indexOf('Chrome') > -1) {
        browser = 'Google Chrome';
        version = userAgent.match(/Chrome\/(\d+\.\d+)/) ? userAgent.match(/Chrome\/(\d+\.\d+)/)[1] : version;
    } else if (userAgent.indexOf('Firefox') > -1) {
        browser = 'Mozilla Firefox';
        version = userAgent.match(/Firefox\/(\d+\.\d+)/) ? userAgent.match(/Firefox\/(\d+\.\d+)/)[1] : version;
    } else if (userAgent.indexOf('Safari') > -1 && userAgent.indexOf('Chrome') === -1) {
        browser = 'Apple Safari';
        version = userAgent.match(/Version\/(\d+\.\d+)/) ? userAgent.match(/Version\/(\d+\.\d+)/)[1] : version;
    } else if (userAgent.indexOf('Trident') > -1) {
        browser = 'Internet Explorer';
        version = userAgent.match(/rv:(\d+\.\d+)/) ? userAgent.match(/rv:(\d+\.\d+)/)[1] : version;
    }
    
    // 检测操作系统
    if (userAgent.indexOf('Windows NT 10.0') > -1) {
        os = 'Windows 10/11';
    } else if (userAgent.indexOf('Windows NT 6.3') > -1) {
        os = 'Windows 8.1';
    } else if (userAgent.indexOf('Windows NT 6.2') > -1) {
        os = 'Windows 8';
    } else if (userAgent.indexOf('Windows NT 6.1') > -1) {
        os = 'Windows 7';
    } else if (userAgent.indexOf('Windows NT 6.0') > -1) {
        os = 'Windows Vista';
    } else if (userAgent.indexOf('Windows NT 5.1') > -1) {
        os = 'Windows XP';
    } else if (userAgent.indexOf('Mac OS X') > -1) {
        os = 'macOS';
        let osVersion = userAgent.match(/Mac OS X (\d+_\d+)/);
        if (osVersion) {
            os += ' ' + osVersion[1].replace('_', '.');
        }
    } else if (userAgent.indexOf('Android') > -1) {
        os = 'Android';
        let osVersion = userAgent.match(/Android (\d+\.\d+)/);
        if (osVersion) {
            os += ' ' + osVersion[1];
        }
    } else if (userAgent.indexOf('iOS') > -1 || userAgent.indexOf('iPhone OS') > -1) {
        os = 'iOS';
        let osVersion = userAgent.match(/(?:iPhone OS|iOS) (\d+_\d+)/);
        if (osVersion) {
            os += ' ' + osVersion[1].replace('_', '.');
        }
    }
    
    // 检测设备类型
    let deviceType = '桌面设备';
    if (userAgent.match(/Mobile|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i)) {
        if (userAgent.match(/iPad/i)) {
            deviceType = '平板设备';
        } else {
            deviceType = '移动设备';
        }
    }
    
    return { browser, version, os, deviceType, original: userAgent };
}

function showDetail(log) {
    // 直接使用传入的日志对象，不需要JSON解析
    
    $('#detail_id').text(log.id);
    
    // 格式化日志类型
    var typeText = log.type;
    switch(log.type) {
        case 'login': typeText = '登录日志'; break;
        case 'email': typeText = '邮件日志'; break;
        case 'resetpwd': typeText = '重置密码'; break;
        case 'verify': typeText = '验证日志'; break;
        case 'action': typeText = '操作日志'; break;
    }
    $('#detail_type').text(typeText);
    
    $('#detail_username').text(log.username || '-');
    $('#detail_action').text(log.action);
    $('#detail_ip').text(log.ip);
    $('#detail_result').text(log.result ? '成功' : '失败');
    $('#detail_time').text(log.create_time);
    
    // 解析并显示User Agent信息
    if (log.user_agent) {
        const parsedUA = parseUserAgent(log.user_agent);
        let userAgentHtml = `原始信息：${parsedUA.original}\n\n`;
        userAgentHtml += `浏览器：${parsedUA.browser} ${parsedUA.version}\n`;
        userAgentHtml += `操作系统：${parsedUA.os}\n`;
        userAgentHtml += `设备类型：${parsedUA.deviceType}`;
        $('#detail_useragent').text(userAgentHtml);
    } else {
        $('#detail_useragent').text('-');
    }
    
    // 显示模态框
    $('#detailModal').modal('show');
}



// 删除指定天数之前的日志
function deleteLog(days) {
    // 定义天数文本
    let dayText = '';
    switch(days) {
        case 7: dayText = '一周'; break;
        case 30: dayText = '一月'; break;
        case 180: dayText = '半年'; break;
        case 365: dayText = '一年'; break;
    }
    
    if(confirm('确定要删除' + dayText + '之前的日志吗？此操作不可恢复！')) {
        $.ajax({
            type: 'POST',
            url: 'log.php',
            data: {
                action: 'delete',
                days: days
            },
            dataType: 'json',
            success: function(data) {
                if(data.code == 1) {
                    alert('删除成功，共删除' + data.count + '条日志');
                    location.reload();
                } else {
                    alert('删除失败：' + data.msg);
                }
            },
            error: function() {
                alert('请求失败，请重试');
            }
        });
    }
}

// 清空所有日志
function deleteAllLog() {
    if(confirm('确定要清空所有日志吗？此操作不可恢复！')) {
        $.ajax({
            type: 'POST',
            url: 'log.php',
            data: {
                action: 'delete_all'
            },
            dataType: 'json',
            success: function(data) {
                if(data.code == 1) {
                    alert('清空成功，共删除' + data.count + '条日志');
                    location.reload();
                } else {
                    alert('清空失败：' + data.msg);
                }
            },
            error: function() {
                alert('请求失败，请重试');
            }
        });
    }
}
</script>